<template>
  <div class="app-container eutr-content">
    <div class="eutr-content-left">
      <el-tree ref="tree" :data="treeData" :props="defaultProps" node-key="id" show-checkbox default-expand-all
        highlight-current @check="handleCheckChange" />
    </div>
    <div class="eutr-content-right">
      <!-- 页面标题 -->
      <div class="page-header">
        <h3 class="page-title">水质对比分析</h3>
      </div>

      <!-- 查询条件区域 -->
      <div class="search-container">
        <el-form :inline="true" class="demo-form-inline">
          <!-- <el-form-item label="时间：">
            <el-date-picker v-model="dateRange" type="daterange" range-separator="到" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item> -->
          <el-form-item label="开始时间:">
            <el-date-picker v-model="startTime" type="date" placeholder="选择日期" format="yyyy-MM-dd"
              value-format="yyyy-MM-dd" style="width: 160px;" />
          </el-form-item>
          <el-form-item label="结束时间:">
            <el-date-picker v-model="endTime" type="date" placeholder="选择日期" format="yyyy-MM-dd"
              value-format="yyyy-MM-dd" style="width: 160px;" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 指标切换标签 -->
      <div class="indicator-tabs">
        <el-radio-group v-model="currentIndicator" size="small" @change="handleIndicatorChange">
          <el-radio-button v-for="value in bussinessItemList" :label="value.itemCode">{{ value.itemName
          }}</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 图表区域 -->
      <div class="chart-container">
        <div id="waterQualityChart" ref="waterQualityChart" style="width: 100%; height: 400px;"></div>
      </div>
    </div>
  </div>
</template>
<script>
import { segmentRegionTree } from '@/api/dataResources/waterJcData/sgMonitor.js'
import { getWaterQualityComparisonAnalysis } from '@/api/riverGeneralMange/riverGeneralMange.js'
import { bussinessItemData } from '@/api/dataResources/waterJcData/sgMonitor'
import * as echarts from 'echarts'

export default {
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 选中的节点数据
      selectedNodes: [],
      dateRange: [],
      // 时间选择
      startTime: this.getDefaultStartTime(),
      endTime: this.getDefaultEndTime(),
      // 当前选择的指标
      currentIndicator: '',
      // 图表实例
      chartInstance: null,
      monitorFactor: '',
      bussinessItemList: '',
      // 图表数据
      chartData: {
        xAxis: [],
        series: {
          month: [],
          lastmonth: [],
          lastyear: []
        }
      },
      // 加载状态
      loading: false
    }
  },
  created() {

  },

  mounted() {
    // 使用async/await确保数据加载和页面渲染的正确顺序
    this.initializePage();
  },

  beforeDestroy() {
    // 组件销毁前销毁图表实例
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  },
  methods: {
    // 页面初始化方法，确保数据加载和页面渲染顺序正确
    async initializePage() {
      try {
        // 首先加载基础数据
        await this.query();
        // 确保页面元素已经渲染完成
        this.$nextTick(() => {
          // 初始化图表
          this.initChart();
          // 确保图表数据已加载
          if (this.chartData) {
            // 如果已有数据，直接更新图表
            this.updateChartData();
          } else {
            // 如果还没有数据，再次尝试获取数据
            this.getWaterQualityComparisonAnalysis().then(() => {
              this.updateChartData();
            });
          }
          this.loading = false;
        });
      } catch (error) {
        console.error('页面初始化失败:', error);
        this.loading = false;
        this.$message.error('页面加载失败，请刷新重试');
      }
    },

    // 获取默认开始时间（当前月的第一天）
    getDefaultStartTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth();
      return new Date(year, month, 1).toISOString().split('T')[0];
    },

    // 获取默认结束时间（当前月的最后一天）
    getDefaultEndTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth();
      return new Date(year, month + 1, 0).toISOString().split('T')[0];
    },
    async getBussinessItemData() {
      try {
        const res = await bussinessItemData({ bussinessCategoryCode: 'Auto' })
        if (res.code == 200) {
          this.bussinessItemList = res.data
          // 如果业务项列表不为空，默认选择第一项
          if (this.bussinessItemList && this.bussinessItemList.length > 0) {
            this.monitorFactor = this.bussinessItemList[0].id
            this.currentIndicator = this.bussinessItemList[0].itemCode
          }
        }
      } catch (error) {
        console.error('Error fetching business items:', error)
      }
    },
    async getWaterQualityComparisonAnalysis() {
      try {
        let res = await getWaterQualityComparisonAnalysis({
          startTime: this.startTime,
          endTime: this.endTime,
          segmentId: this.selectedNodes.map(node => node.id).join(','),
          itemId: this.currentIndicator
        })
        if (res.code == 200) {
          // 存储API返回的数据
          let resData = res.data;
          this.chartData.xAxis = resData.segment;
          this.chartData.series =  {
            month: resData.month,
            lastmonth: resData.lastmonth,
            lastyear: resData.lastyear
          }
          // 直接绘制图表
          if (this.chartInstance) {
            const option = this.getChartOption();
            this.chartInstance.setOption(option);
          }
        }
      } catch (error) {
        console.error('获取水质对比分析数据失败:', error)
        this.$message.error('获取数据失败，请稍后重试')
      }
    },
    async query() {
      try {
        // 等待所有必要的数据都加载完成
        await this.getRegonTree();
        await this.getBussinessItemData();
        // 等待图表数据加载完成
        await this.getWaterQualityComparisonAnalysis();
      } catch (error) {
        console.error('数据查询失败:', error);
        throw error; // 向上抛出错误，让调用者知道查询失败
      }
    },
    // 处理树节点勾选事件
    handleCheckChange(data, checkedInfo) {
      // 获取所有选中的节点
      this.selectedNodes = this.$refs.tree.getCheckedNodes(true);
      // 只保留二级节点（叶子节点）
      this.selectedNodes = this.selectedNodes.filter(node => !node.children || node.children.length === 0);
      // 当选中节点变化时，更新图表
      this.updateChartData();
    },

    // 初始化图表
    initChart() {
      // 获取图表容器
      const chartDom = this.$refs.waterQualityChart;
      if (!chartDom) return;

      // 如果已有图表实例，先销毁
      if (this.chartInstance) {
        this.chartInstance.dispose();
      }

      // 创建ECharts实例
      this.chartInstance = echarts.init(chartDom);

      // 设置图表配置项
      const option = this.getChartOption();
      this.chartInstance.setOption(option);

      // 强制重新计算尺寸，确保正确渲染
      setTimeout(() => {
        if (this.chartInstance) {
          this.chartInstance.resize();
        }
      }, 100);

      // 添加窗口大小变化时的图表自适应
      window.addEventListener('resize', () => {
        if (this.chartInstance) {
          this.chartInstance.resize();
        }
      });
    },

    // 获取图表配置项
    getChartOption() {
      // 确保chartData存在并有数据，否则返回空数据配置
      const chartData = this.chartData || {
        xAxis: [],
        series: {
          month: [],
          lastmonth: [],
          lastyear: []
        }
      };
      // 处理数据类型，将字符串转换为数字，处理null值
      const processData = (arr) => {
        return arr.map(item => {
          if (item === null || item === undefined || item === '') {
            return 0; // 将null/undefined/空字符串转换为0，确保图表能显示
          }
          // 将字符串转换为数字
          const numValue = parseFloat(item);
          return isNaN(numValue) ? 0 : numValue;
        });
      };
      
      // 处理所有数据
      const processedMonth = processData(chartData.series.month || []);
      const processedLastMonth = processData(chartData.series.lastmonth || []);
      const processedLastYear = processData(chartData.series.lastyear || []);
      
      // 计算最大值用于Y轴设置
      const allData = [...processedMonth, ...processedLastMonth, ...processedLastYear];
      const maxValue = allData.length > 0 ? Math.max(...allData) : 8;
      const baseValue = maxValue > 0 ? maxValue * 1.2 : 8; // 增加20%的边距以更好地显示数据
      const safeMaxValue = Number(baseValue.toFixed(2)); // 最多保留两位小数
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#e4e7ed',
          borderWidth: 1,
          textStyle: {
            color: '#303133'
          },
          formatter: (params) => {
            let result = `${params[0].name}<br/>`;
            params.forEach(item => {
              result += `${item.marker}${item.seriesName}: ${item.value} ${this.getIndicatorUnit(this.currentIndicator)}<br/>`;
            });
            return result;
          }
        },
        // 图例配置，显示在图表上方
        legend: {
          data: ['当期', '环比', '同比'],
          top: 10,
          left: 'center',
          textStyle: {
            color: '#606266',
            fontSize: 12
          },
          itemWidth: 16,
          itemHeight: 16,
          itemGap: 20,
          formatter: function (name) {
            return name;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: chartData.xAxis,
          axisLabel: {
            rotate: 45,
            color: '#606266',
            fontSize: 12,
            interval: 0
          },
          axisLine: {
            lineStyle: {
              color: '#dcdfe6'
            }
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          name: this.getIndicatorUnit(this.currentIndicator),
          nameTextStyle: {
            color: '#606266',
            fontSize: 12,
            padding: [0, 0, 0, 40]
          },
          axisLabel: {
            color: '#606266',
            fontSize: 12,
            formatter: (value) => {
              return value;
            }
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#dcdfe6'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0',
              type: 'dashed'
            }
          },
          min: 0,
          max: safeMaxValue
        },
        series: [
          {
            name: '当期',
            type: 'bar',
            data: processedMonth,
            itemStyle: {
              color: '#1890ff'
            },
            barWidth: '20%',
            emphasis: {
              focus: 'series',
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            animationDelay: function (idx) {
              return idx * 100;
            }
          },
          {
            name: '环比',
            type: 'bar',
            data: processedLastMonth,
            itemStyle: {
              color: '#52c41a'
            },
            barWidth: '20%',
            emphasis: {
              focus: 'series',
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            animationDelay: function (idx) {
              return idx * 100 + 30;
            }
          },
          {
            name: '同比',
            type: 'bar',
            data: processedLastYear,
            itemStyle: {
              color: '#fa8c16'
            },
            barWidth: '20%',
            emphasis: {
              focus: 'series',
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            animationDelay: function (idx) {
              return idx * 100 + 60;
            }
          }
        ],
        animationEasing: 'elasticOut',
        animationDelayUpdate: function (idx) {
          return idx * 5;
        }
      }
      return option;
    },

    // 根据指标获取单位
    getIndicatorUnit(indicator) {
      const unitMap = this.bussinessItemList.find(item => item.itemCode === indicator)?.unit
      return unitMap
    },

    // 更新图表数据
    updateChartData() {
      if (this.chartInstance) {
        const option = this.getChartOption();
        this.chartInstance.setOption(option);
      }
    },

    // 查询按钮点击事件
    async handleQuery() {
      // 检查日期是否选择
      if (!this.startTime || !this.endTime) {
        this.$message.warning('请选择完整的时间范围');
        return;
      }

      // 检查开始时间是否小于结束时间
      if (new Date(this.startTime) > new Date(this.endTime)) {
        this.$message.warning('开始时间不能晚于结束时间');
        return;
      }

      // 直接调用API方法获取数据并更新图表
      await this.getWaterQualityComparisonAnalysis();
    },

    // 指标切换事件
    handleIndicatorChange(item) {
      this.monitorFactor = item.value
      this.handleQuery()
    },
    async delay(time){
      return new Promise(resolve => setTimeout(resolve, time));
    },
    async getRegonTree() {
      try {
        const res = await segmentRegionTree({segmentType: "IsAuto", segmentTypeDrink: "filter"});
        if (res.code == 200) {
          this.treeData = this.convertToTree(res.data || []);
          await this.delay(100);

          // 延迟执行，确保DOM已经渲染
            const findAllLeafNodes = (nodes) => {
              let leafNodes = [];
              nodes.forEach(node => {
                if (!node.children || node.children.length === 0) {
                  leafNodes.push(node);
                } else {
                  leafNodes = leafNodes.concat(findAllLeafNodes(node.children));
                }
              });
              return leafNodes;
            };

            // 获取所有叶子节点
            const leafNodes = findAllLeafNodes(this.treeData);

            // 默认选中所有叶子节点
            if (this.$refs.tree && leafNodes.length > 0) {
              this.$refs.tree.setCheckedNodes(leafNodes);
              // 更新selectedNodes
              this.selectedNodes = this.$refs.tree.getCheckedNodes(true);
              // 只保留二级节点（叶子节点）
              this.selectedNodes = this.selectedNodes.filter(node => !node.children || node.children.length === 0);
            }
        }
      } catch (error) {
        this.$message.error('获取区域树数据失败，请稍后重试');
      }
    },
    convertToTree(list) {
      // 创建一个映射表，用于快速查找节点
      const map = {};
      const treeData = [];

      // 初始化所有节点
      list.forEach(item => {
        map[item.id] = {
          id: item.id,
          label: item.name,
          ...item,
          children: []
        };
      });

      // 构建树形结构
      list.forEach(item => {
        const node = map[item.id];
        if (item.pId === '0' || !item.pId) {
          // 根节点
          treeData.push(node);
        } else {
          // 子节点
          const parent = map[item.pId];
          if (parent) {
            parent.children.push(node);
          } else {
            // 如果找不到父节点，则作为根节点处理
            treeData.push(node);
          }
        }
      });

      return treeData;
    }
  }
}
</script>
<style lang="scss" scoped>
.eutr-content {
  display: flex;
  height: 100%;
  min-height: 600px;
  justify-content: space-between;
}

.eutr-content-left {
  width: 300px;
  height: 100%;
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  // border-right: 1px solid #e4e7ed;
  // overflow-y: auto;
}

.eutr-content-right {
  width: calc(100% - 320px);
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  height: 100%;
  overflow-y: auto;
}

.selected-count {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 4px 12px;
  border-radius: 10px;
  font-size: 14px;
  margin-bottom: 15px;
  display: inline-block;
}

// 页面标题样式
.page-header {
  margin-bottom: 10px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

// 查询条件区域样式
.search-container {}

.demo-form-inline {
  display: flex;
  align-items: center;
}

// 指标切换标签样式
.indicator-tabs {
  margin-bottom: 15px;
}

// 图例区域样式
.legend-container {
  display: flex;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 2px;
  margin-right: 8px;
  display: inline-block;
}

.legend-color.current {
  background-color: #1890ff;
}

.legend-color.ring {
  background-color: #52c41a;
}

.legend-color.year {
  background-color: #fa8c16;
}

// 响应式设计
@media screen and (max-width: 1200px) {
  .eutr-content {
    flex-direction: column;
  }

  .eutr-content-left {
    width: 100%;
    height: auto;
    max-height: 300px;
    border-right: none;
    border-bottom: 1px solid #e4e7ed;
  }

  .eutr-content-right {
    width: 100%;
  }

  .chart-container {
    height: 350px;
  }
}

@media screen and (max-width: 768px) {
  .demo-form-inline {
    flex-direction: column;
    align-items: stretch;
  }

  .demo-form-inline .el-form-item {
    margin-bottom: 15px;
  }

  .indicator-tabs {
    white-space: nowrap;
  }

  .chart-container {
    height: 300px;
  }

  .legend-container {
    flex-wrap: wrap;
  }

  .legend-item {
    margin-bottom: 10px;
  }
}

.legend-text {
  font-size: 14px;
  color: #606266;
}

// 图表区域样式
.chart-container {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  height: 420px;
}
</style>